import { defineStore } from "pinia";
import {
  getStorage,
  setStorage,
  removeStorage,
} from "@/utils/storage/index.js";
import { login, logout, getInfo } from "@/utils/api.js";
import { getToken, setToken, removeToken } from "@/utils/auth.js";

export const TOKEN_KEY = "TOKEN";

export const useAuthStore = defineStore({
  id: "auth",
  state: () => ({
    token: getToken() || getStorage("TOKEN_KEY"),
    permissions: [],
    roles: [],
    user: {},
    getPermissioned: false,
  }),
  getters: {
    getToken: (state) => state.token,
    isLogin: (state) => !!state.token,
  },
  actions: {
    initToken() {
      this.token = getToken();
    },
    setToken(token) {
      setToken(token);
      setStorage(TOKEN_KEY, token, 0);
      this.token = token;
    },
    async login(params) {
      try {
        const data = await login(params);
        this.setToken(data.token);
        this.getInfo();
        return Promise.resolve(data);
      } catch (err) {
        return Promise.reject(err);
      }
    },
    // 获取用户信息
    getInfo() {
      this.getPermissioned = true;
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.user;
            this.user = user;
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = res.roles;
              this.permissions = res.permissions;
            } else {
              this.roles = [];
              this.permissions = [];
            }
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    async logout() {
      try {
        const res = await logout();
        removeStorage(TOKEN_KEY);
        removeToken();
        this.setToken(undefined);
        return Promise.resolve(res);
      } catch (err) {
        return Promise.reject(err);
      }
    },
  },
});
